package com.duowan.realtime.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.WebUtils;

import com.duowan.realtime.model.SqlJob;
import com.duowan.realtime.model.builder.SqlJobBuilder;
import com.duowan.realtime.model.builder.SqlJobBuilderImpl;
import com.duowan.realtime.model.builder.SqlJobDirector;
import com.duowan.realtime.service.SqlJobService;

/**
 * @version 1.0
 * @author: tangsicheng
 * @date: 14-8-27
 * @since 1.0
 */


@Controller
public class SqlJobController {
    private static final Logger logger = LoggerFactory.getLogger(SqlJobController.class);
    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private SqlJobService sqlJobService;

    @RequestMapping("/sqlJobIndex")
    public String sqlJobIndex(HttpServletRequest request, ModelMap model) {
        return "/sqlJobIndex";

    }
    
    @RequestMapping("/sqlJobManage")
    public String sqlJobManage(HttpServletRequest request, ModelMap model) {
        initParameter(model);
        return "/sqlJobManage";

    }

	private void initParameter(ModelMap model) {
		List<SqlJob> sqlJobList = sqlJobService.getAllSqlJobs();
        model.put("sqlJobList", sqlJobList);
	}
    
    @RequestMapping("/sqlJob")
    public String showSqlJob(HttpServletRequest request, ModelMap model) {
        initParameter(model);
        return "/sqlJob";

    }
    
    @RequestMapping("/editSqlJob")
    public String editSqlJob(HttpServletRequest request, ModelMap model, String sqlId) {
    	initParameter(model);
    	SqlJob sqlJob = sqlJobService.getById(sqlId);
        model.put("sqlJob", sqlJob);
        return "/editSqlJob";

    }
    
    

    @RequestMapping
    public void addSqlJob(HttpServletRequest request, HttpServletResponse response,SqlJob sqlJob) throws IOException {
        Map<String, String> result = new HashMap<String, String>();
        PrintWriter writer = response.getWriter();
        try {
//            String sqlName = request.getParameter("sqlName");
//            System.out.println("sqlName:"+sqlName);
//            Assert.hasLength(sqlName, "sqlName 不能为空。");
//            String kpiCode = request.getParameter("kpiCode");
//            List<String> dimList = getDimList(request);
//            SqlJob newSqlJob = getSqlJobEntity(sqlName, kpiCode, dimList);
            sqlJobService.create(sqlJob);

            result.put("status", "1");
        }
        catch (Exception e) {
            logger.error("insert get some wrong :" + e.getMessage());
            result.put("status", "0");
            result.put("message", e.getMessage());
        }
        writer.write(objectMapper.writeValueAsString(result));
    }

    @RequestMapping
    public void deleteSqlJob(HttpServletRequest request, HttpServletResponse response, String sqlId) throws IOException {
        Map<String,String> result = new HashMap<String, String>();
        PrintWriter writer = response.getWriter();
        try {
            sqlJobService.removeById(sqlId);
            result.put("status", "1");
        }catch(Exception e) {
            logger.error("remove the" + sqlId + " bfgroup get some wrong ", e);
            result.put("status", "0");
            result.put("message", e.getMessage());
        }
        writer.write(objectMapper.writeValueAsString(result));
    }

    private List<String> getDimList(HttpServletRequest request) {
        List<String> resutList = new ArrayList<String>();
        Map<String,Object> dimMaps = WebUtils.getParametersStartingWith(request,"dim");
        Set<String> keySet = dimMaps.keySet();
        for(String key:keySet){
            resutList.add((String) dimMaps.get(key));
        }
        return resutList;
    }

    private SqlJob getSqlJobEntity(String sqlName, String kpiCode, List<String> dimList){
        SqlJobDirector director = new SqlJobDirector();
        SqlJobBuilder builder = new SqlJobBuilderImpl();
        director.setSqlJobBuilder(builder);
        director.construct(sqlName,kpiCode,dimList);
        return builder.getResult();
    }
    
    @RequestMapping
	public void update(SqlJob sqlJob,String sqlId, HttpServletRequest request,HttpServletResponse response) throws IOException {
		Map<String,String> result = new HashMap<String, String>();
		if (StringUtils.isNotBlank(sqlId)) {
			sqlJob.setSqlId(sqlId);
		}
		PrintWriter writer = response.getWriter();
		try {
			sqlJobService.update(sqlJob);
			result.put("status", "1");
		}catch(Exception e) {
			logger.error("update get some wrong :" + e.getMessage());
			result.put("status", "0");
			result.put("message", e.getMessage());			
		}
		writer.write(objectMapper.writeValueAsString(result));
	}


}
